#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单的图片上传服务器
支持拖拽上传和图片管理
"""

import os
import http.server
import socketserver
import urllib.parse
import cgi
import json
from datetime import datetime

# 上传目录
UPLOAD_DIR = "static/uploads"
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR, exist_ok=True)

class UploadHandler(http.server.SimpleHTTPRequestHandler):
    """处理文件上传和图片管理"""
    
    def do_GET(self):
        """处理GET请求"""
        if self.path == '/api/images':
            self.handle_get_images()
        elif self.path.startswith('/uploads/'):
            # 提供上传的文件
            filename = os.path.basename(self.path)
            file_path = os.path.join(UPLOAD_DIR, filename)
            if os.path.exists(file_path):
                self.serve_file(file_path)
            else:
                self.send_error(404)
        else:
            # 其他请求使用默认处理
            super().do_GET()
    
    def do_POST(self):
        """处理POST请求"""
        if self.path == '/api/upload-image':
            self.handle_upload()
        elif self.path == '/api/delete-image':
            self.handle_delete()
        else:
            self.send_error(404)
    
    def handle_get_images(self):
        """获取图片列表"""
        try:
            images = []
            for filename in os.listdir(UPLOAD_DIR):
                if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.webp')):
                    file_path = os.path.join(UPLOAD_DIR, filename)
                    file_stat = os.stat(file_path)
                    images.append({
                        'name': filename,
                        'url': f'/uploads/{filename}',
                        'size': file_stat.st_size
                    })
            
            self.send_json_response({'success': True, 'images': images})
        except Exception as e:
            self.send_json_response({'success': False, 'message': str(e)}, 500)
    
    def handle_upload(self):
        """处理文件上传"""
        try:
            # 解析multipart/form-data
            content_type = self.headers.get('Content-Type', '')
            if 'multipart/form-data' not in content_type:
                self.send_json_response({'success': False, 'message': '只支持multipart/form-data'}, 400)
                return
            
            # 获取boundary
            boundary = content_type.split('boundary=')[1].strip('"')
            
            # 读取请求体
            content_length = int(self.headers.get('Content-Length', 0))
            post_data = self.rfile.read(content_length)
            
            # 解析multipart数据
            parts = post_data.split(f'--{boundary}'.encode())
            
            for part in parts:
                if b'filename=' in part and b'Content-Type:' in part:
                    # 提取文件名
                    filename_start = part.find(b'filename="') + 10
                    filename_end = part.find(b'"', filename_start)
                    filename = part[filename_start:filename_end].decode('utf-8')
                    
                    # 提取文件数据
                    header_end = part.find(b'\r\n\r\n')
                    file_data = part[header_end + 4:]
                    
                    # 移除末尾的boundary标记
                    if file_data.endswith(b'\r\n'):
                        file_data = file_data[:-2]
                    
                    # 生成安全的文件名
                    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                    safe_filename = f"{timestamp}_{filename}"
                    safe_filename = safe_filename.replace(' ', '_').replace('..', '_')
                    
                    # 保存文件
                    file_path = os.path.join(UPLOAD_DIR, safe_filename)
                    with open(file_path, 'wb') as f:
                        f.write(file_data)
                    
                    # 返回成功响应
                    self.send_json_response({
                        'success': True,
                        'imageUrl': f'/uploads/{safe_filename}',
                        'message': '图片上传成功'
                    })
                    return
            
            self.send_json_response({'success': False, 'message': '未找到图片文件'}, 400)
        except Exception as e:
            print(f"上传错误: {e}")
            self.send_json_response({'success': False, 'message': f'上传失败: {str(e)}'}, 500)
    
    def handle_delete(self):
        """处理文件删除"""
        try:
            content_length = int(self.headers.get('Content-Length', 0))
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            
            image_url = data.get('imageUrl', '')
            if not image_url:
                self.send_json_response({'success': False, 'message': '缺少图片URL'}, 400)
                return
            
            filename = os.path.basename(image_url)
            file_path = os.path.join(UPLOAD_DIR, filename)
            
            if os.path.exists(file_path):
                os.remove(file_path)
                self.send_json_response({'success': True, 'message': '图片删除成功'})
            else:
                self.send_json_response({'success': False, 'message': '图片文件不存在'}, 404)
        except Exception as e:
            self.send_json_response({'success': False, 'message': str(e)}, 500)
    
    def serve_file(self, file_path):
        """提供文件服务"""
        try:
            with open(file_path, 'rb') as f:
                content = f.read()
            
            # 设置正确的MIME类型
            content_type = 'application/octet-stream'
            if file_path.endswith('.jpg') or file_path.endswith('.jpeg'):
                content_type = 'image/jpeg'
            elif file_path.endswith('.png'):
                content_type = 'image/png'
            elif file_path.endswith('.gif'):
                content_type = 'image/gif'
            elif file_path.endswith('.webp'):
                content_type = 'image/webp'
            
            self.send_response(200)
            self.send_header('Content-Type', content_type)
            self.send_header('Content-Length', str(len(content)))
            self.end_headers()
            self.wfile.write(content)
        except Exception as e:
            self.send_error(500, str(e))
    
    def send_json_response(self, data, status=200):
        """发送JSON响应"""
        response_json = json.dumps(data, ensure_ascii=False)
        self.send_response(status)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
        self.wfile.write(response_json.encode('utf-8'))

def main():
    """主函数"""
    PORT = 8082  # 使用8082端口
    
    # 切换到magazine目录
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    
    with socketserver.TCPServer(("", PORT), UploadHandler) as httpd:
        print(f"🚀 图片上传服务器启动!")
        print(f"📱 请访问: http://localhost:{PORT}")
        print(f"🧪 上传测试: http://localhost:{PORT}/static/upload-test.html")
        print(f"📁 上传目录: {UPLOAD_DIR}")
        print(f"🔧 按 Ctrl+C 停止服务器")
        
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n👋 服务器已停止")
            httpd.shutdown()

if __name__ == "__main__":
    main()